/*
    nspire-gamekit - a simple homebrew game framework
    Copyright (C) 2011  Daniel Tang

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
//This is going to be so inefficient it's not funny
#include <os.h>
#include "screen.h"
#include "collision.h"

int gameCollisionCheckBuffers(void* buffer1, void* buffer2, uint32_t size);

#define rectIntersects(x1, y1, w1, h1, x2, y2, w2, h2)  \
            ( ((x2 > x1) && (x2 < (x1 + w1))) &&        \
              ((y2 > y1) && (y2 < (y1 + h1))) ) ||      \
            ( ((x1 > x2) && (x1 < (x2 + w2))) &&        \
              ((y1 > y2) && (y1 < (y2 + h2))) )

int gameCheckCollision( NGKPoint point1, NGKScreenBuffer* buffer1, 
                        NGKPoint point2, NGKScreenBuffer* buffer2) {
    NGKPosInt x1 = point1.x, x2 = point2.x, y1 = point1.y, y2 = point2.y;
    if (!rectIntersects( x1, y1, screenBufferWidth(buffer1), screenBufferHeight(buffer1),
                        x2, y2, screenBufferWidth(buffer2), screenBufferHeight(buffer2)))
        return 0;
    
    //Make buffer1 the smaller one
    int32_t tmpint;
    NGKScreenBuffer* tmpbuffer;
    if (screenBufferWidth(buffer1) * screenBufferHeight(buffer1) > 
        screenBufferWidth(buffer2) * screenBufferHeight(buffer2)) {
            tmpint = x1;
            x1 = x2;
            x2 = tmpint;
            
            tmpint = y1;
            y1 = y2;
            y2 = tmpint;
            
            tmpbuffer = buffer1;
            buffer1 = buffer2;
            buffer2 = tmpbuffer;
    }
    
    int ret;
    //Here's where it's going to get REAL slow
    tmpbuffer = screenBufferAlloc(NGKSizeMake(screenBufferWidth(buffer1),screenBufferHeight(buffer1)));
    if (!tmpbuffer) return 0;
    screenBufferClear(0x00, tmpbuffer);
    screenBufferDrawScreen(NGKPointMake(x2 - x1, y2 - y1), buffer2, tmpbuffer);
    ret = gameCollisionCheckBuffers(screenBufferData(tmpbuffer), screenBufferData(buffer1), screenBufferWidth(buffer1) * screenBufferHeight(buffer1));
    screenBufferDestroy(tmpbuffer);
    return ret;
}